
/** 19. 删除链表的倒数第N个节点
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let dummy = new ListNode(-1);
    dummy.next = head;
    let deleteNode = getDeleteNode(dummy, n);
    deleteNode.next = deleteNode.next.next;
    return dummy.next;
};

function getDeleteNode(head, k){
    let p1 = head, p2 = head;
    for(let i = 0; i<k ; i++){
        p1 = p1.next;
    }
    while(p1.next != null){
        p1=p1.next;
        p2=p2.next
    }
    return p2;
}

// 141. 环形链表
var hasCycle = function(head) {
    let slow = head, fast = head;
    while(fast !== null && fast.next !== null){
        slow=slow.next;
        fast = fast.next.next;
        if(fast === slow) return true;
    }
    return false;
};


//876. 链表的中间结点
var middleNode = function(head) {
    let slow = head, fast = head;
    while(fast !== null && fast.next !== null){
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
};

// 206. 反转链表
function reverseList(head) {
    if (head == null || head.next == null) return head;
    let pre = null;
    let cur = head, next = head;
    while (cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
};

// 160 相交链表
var getIntersectionNode = function(headA, headB) {
    let p = headA, q = headB;
    while(p != q){
        p = p ? p.next: headB;
        q = q ? q.next: headA;
    }
    return p;
};

// 234. 回文链表
var isPalindrome = function(head) {
    let res = [];
    while(head !== null){
        res.push(head.val);
        head = head.next;
    }

    for(let i = 0, j = res.length-1; i<=j; i++, j--){
        if(res[i] !== res[j]) return false;
    }
    return true;
};